package org.merak.core.persistence.jdbc;

import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.merak.core.Application;
import org.merak.core.model.ProgrammaticException;

class RecoveryJob extends TimerTask {

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private final long        interval = 20000;
	private final Logger      logger   = Application.database.getLogger();
	private final Timer       timer    = new Timer();
	private final XConnection conn;

	//~ Constructors /////////////////////////////////////////////////////////////
	//****************************************************************************
	public RecoveryJob(XConnection conn) {
		this.conn = conn;
	}

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public void run() {

		// Try connecting...
		try {
			this.conn.connect();
		}
		// Try connecting later
		catch(SQLException ex) {this.logger.warn(
			this.conn.getSettings() +
			": Reconnection attempt will occur after " + (this.interval/1000) + "s"
		);}
		// Detect if connection failed due to bug
		catch (Exception e) {throw new ProgrammaticException(
			this.conn.getSettings() + ": bugs are preventing connection.",e
		);}
		// Kill this timer if connection has been restored
		finally {
			try {
				if (!this.conn.isClosed()) {
					this.logger.warn(this.conn.getSettings() + ": Connection has been restored");
					this.timer.cancel();
				}
			} catch (SQLException e) {}
		}

	}
	//****************************************************************************
	public void start() {

	    this.timer.scheduleAtFixedRate(this, 0, this.interval);

	}
	//****************************************************************************

}
